let currentPage = 1; // 当前页码
let totalPages = 1; // 总页数
let isLoading = false; // 加载状态标记

let hasMorePosts = true;
let currentPostId = null;
// 监听滚动事件
window.addEventListener('scroll', checkScroll);

function checkScroll() {
    // 如果正在加载或没有更多帖子，则不执行任何操作
    if (isLoading || !hasMorePosts) return;

    // 计算是否接近页面底部
    const scrollHeight = document.documentElement.scrollHeight;
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    const clientHeight = document.documentElement.clientHeight;

    if (scrollTop + clientHeight >= scrollHeight - 300) {
        loadMorePosts();
        console.log("监测成功一次")
    }
}


function loadMorePosts() {
    isLoading = true;

    // 显示加载指示器
    const loadingIndicator = document.createElement('div');
    loadingIndicator.className = 'loading-indicator';
    loadingIndicator.innerHTML = '<i class="iconfont">&#xe60f;</i> 加载中...';
    document.querySelector('.top-story-content-attention').appendChild(loadingIndicator);

    // 使用$.ajax发送请求获取更多帖子
    $.ajax({
        url: `/mainPageAttention/more?pageNum=${currentPage + 1}`,
        type: 'GET',
        success: function (result) {
            console.log(result);

            if (!result.allPosts || !result.allPosts || result.allPosts.length === 0) {
                hasMorePosts = false;
                loadingIndicator.innerHTML = '没有更多内容了';
                setTimeout(() => loadingIndicator.remove(), 2000);
                return;
            }

            const posts = result.allPosts;
            const users = result.allUsers || [];
            const container = document.querySelector('.top-story-content-attention'); // 确保容器存在

            // 生成模板字符串
            const html = posts.map((post, postIndex) => {
                const user = users[postIndex] || {}; // 假设用户列表与帖子列表一一对应
                const isLiked = post.isLiked === 1 || post.isLiked === '1' ? 'liked' : ''; // 点赞状态类名

                return `
                
                    <div class="top-story-content-detail2 article-container">
                        <a href="/posts/select/id?id=${post.id}" style="color: black">
                            <div class="top-story-content-head">
                                <h3>${post.title || '无标题'}</h3>
                            </div>
                        </a>
                        <div id="content">
                            <div class="top-story-content-detail-list">
                                <p class="top-story-content-detail-list-p pattention-top-story-content-detail-list-p">
                                    <a href="/posts/select/id?id=${post.id}" style="color: black">
                                        <!-- 用户信息循环（假设每个帖子对应一个用户） -->
                                        <span class="pattention-user-information">
                                            <img src="${user.avatar || '../static/img/OIP-C.jpg'}" alt="${user.username || '未知用户'}">
                                            <span>${user.username || '未知用户'}</span>
                                            <i class="word-introduction">${user.bio || ''}&nbsp;&nbsp;</i>
                                        </span>
                                        <i class="pattention-empty">${post.content || '暂无内容'}</i>
                                    </a>
                                </p>
                                <span class="pattention-read-full-text">
                                    <i class="iconfont">&#xe60d;</i>阅读全文<i class="iconfont">&#xe7d1;</i>
                                </span>
                            </div>
                            <div class="content-right">
                                ${post.imageUrl ?
                    `<img src="${post.imageUrl}" alt="文章图片" class="img-content">` :
                    `<img src="../static/img/OIP-C.jpg" alt="默认图片" class="img-content">`
                }
                            </div>
                        </div>
                        <div class="top-story-content-footer">
                            <button class="top-story-content-footer-button top-story-content-footer-button-start" 
                                    data-post-id="${post.id}" 
                                    onclick="articleDetail(this.dataset.postId)">
                                <i class="iconfont comment">&#xe619;</i>
                                <span>${post.commentCount || 0}</span>条评论
                            </button>
                            <button class="top-story-content-footer-button top-story-content-footer-button-share">
                                <i class="iconfont share">&#xe60e;</i>分享
                            </button>
                            <button class="top-story-content-footer-button top-story-content-footer-button-like ${isLiked}" 
                                    data-post-id="${post.id}" 
                                    data-is-liked="${post.isLiked || 0}">
                                <i class="iconfont like ${isLiked}">&#xe610;</i>喜欢
                            </button>
                            <button class="top-story-content-footer-button top-story-content-footer-button-more">
                                <a  th:href="@{/toReportOthers/?postId={id}(id=${post.id})}" style="color: rgba(169, 178, 185, 0.937);">
                            <i class="iconfont more">&#xe621;</i>
                            举报
                            </a>
                            </button>
                            <div class="share-outer">
                                <div class="share-detail">
                                    <i class="iconfont">&#xe618;</i>
                                    <span>复制链接</span>
                                </div>
                            </div>
                        </div>
                        <div class="comment-publish">
                            <div class="comment-input-outer">
                                <div class="comment-input">
                                    <input type="text" placeholder="留下你的精彩评论吧" class="comment-input-detail"  data-value="${post.id}">
                                    <div class="input-icons">
                                        <i class="iconfont">&#xe642;</i>
                                        <span class="emoji-icon" data-post-id="${post.id}" onclick="publish(this.dataset.postId)">发布</span>
                                    </div>
                                </div>
                            </div>
                            <div class="comment-item-outer"  data-value="${post.id}"></div> <!-- 评论动态加载 -->
                        </div>
                    </div>
                
                `;
            }).join('');

            // 将新内容插入到容器中
            if (container) {
                container.insertAdjacentHTML('beforeend', html);
            } else {
                console.error('容器元素未找到，请检查类名是否正确');
            }

            // 更新页码和状态
            currentPage++;
            loadingIndicator.remove();
            isLoading = false;

            // 初始化点赞按钮事件（优化版）
            const likeButtons = document.querySelectorAll('.top-story-content-footer-button-like');
            likeButtons.forEach((button, index) => {
                button.addEventListener('click', function () {
                    const postId = this.dataset.postId;
                    const isCurrentlyLiked = this.classList.contains('liked');
                    const icon = this.querySelector('.like');

                    // 发送点赞/取消点赞请求
                    $.ajax({
                        url: isCurrentlyLiked ? `/posts/cancelLike?postId=${postId}` : `/posts/like?postId=${postId}`,
                        type: 'POST',
                        success: function (result) {
                            if (result.success) {
                                // 更新状态
                                this.classList.toggle('liked');
                                icon.classList.toggle('liked');
                                // 示例：更新点赞数（需后端返回新数据）
                                // const commentCount = this.previousElementSibling.querySelector('span');
                                // commentCount.textContent = result.likeCount;
                                showCustomAlert(isCurrentlyLiked ? '取消点赞成功' : '点赞成功', 2000);
                            }
                        }.bind(this), // 绑定this上下文
                        error: function (error) {
                            showCustomAlert(`操作失败: ${error.statusText}`, 3000);
                        }
                    });
                });
            });
        },
        error: function (error) {
            console.error('加载更多失败:', error);
            loadingIndicator.innerHTML = '加载失败，请重试';
            setTimeout(() => loadingIndicator.remove(), 2000);
            isLoading = false;
        }
    });
}
const articleContainers = document.querySelector('.top-story-container');

// 监听父容器的点击事件
articleContainers.addEventListener('click', function(event) {
    const target = event.target; // 点击的目标元素
console.log('目标元素是'+target)
    // 检查目标是否是 "read-full-text" 元素
    if (target.classList.contains('pattention-read-full-text')) {
        handleReadFullTextClick(target);
        console.log('开始处理'+'事件')
    }
    // 处理评论按钮的展开/收起
    if (target.classList.contains('top-story-content-footer-button-start')) {
        console.log('处理阅读全文按钮')
        // 1. 向上找到文章容器
        const articleContainer = target.closest('.article-container');
        // 2. 从文章容器中向下查找评论区域
        const commentPublish = articleContainer.querySelector('.comment-publish');
        const isExpanded = target.innerHTML.includes('收起评论');
        if (isExpanded) {
            console.log('if')
            commentPublish.style.display = 'none';
            target.innerHTML = `<i class="iconfont comment" >&#xe619;</i> ${target.value}条评论`;
        } else {
            commentPublish.style.display = 'block';
            target.innerHTML = `<i class="iconfont comment" >&#xe619;</i> 收起评论`;
        }
    }

    // 处理查看评论的逻辑（调用 articleDetail）
    if (target.classList.contains('top-story-content-footer-button-start')) {
        const postId = target.dataset.value;
        articleDetail(postId);
    }

});
// });

// 处理阅读全文/收起的逻辑（单独封装函数）
function handleReadFullTextClick(triggerElement) {
    // 通过 triggerElement 找到对应的外层容器（article-container）
    const articleContainer = triggerElement.closest('.article-container');

    // 获取容器内的相关元素
    const targetParagraph = articleContainer.querySelector('.pattention-empty');

    // const userName = articleContainer.querySelector('.user-name');
    const contentRight = articleContainer.querySelector('.content-right');
    const detailList = articleContainer.querySelector('.top-story-content-detail-list');
    const readFullText = articleContainer.querySelector('.pattention-read-full-text');

    // 使用 window.getComputedStyle 获取元素的实际高度
    const currentHeight = window.getComputedStyle(targetParagraph).height;
console.log(currentHeight)
    if (currentHeight === '49px') {
        console.log(currentHeight+'1')
        console.log(5656)
        console.log(targetParagraph)
        console.log(contentRight)
        console.log(detailList)
        console.log(readFullText)
        targetParagraph.style.height = 'auto';
        targetParagraph.style.display = 'block';

        targetParagraph.classList.add('content');

        detailList.style.width = '100%';
        readFullText.innerHTML = '<i class="iconfont">&#xe60d;</i>收起<i class="iconfont">&#xe6b8;</i>';
        contentRight.style.display = 'none';
        console.log(targetParagraph)

        console.log(detailList)
        console.log(readFullText)
        console.log(currentHeight+'2')
    } else {
        console.log(currentHeight+'3')
        targetParagraph.style.height = '49px';
        readFullText.innerHTML = '<i class="iconfont">&#xe60d;</i>阅读全文<i class="iconfont">&#xe7d1;</i>';
        targetParagraph.style.display = '-webkit-box';


        targetParagraph.classList.remove('content');
        contentRight.style.display = 'block';
        detailList.style.width = '74%';

    }
}
function articleDetail(postId) {
    const postIdNum = Number(postId);
    const comment_item_outers = document.getElementsByClassName('comment-item-outer');
    let comment_item_outer;
    for(let i=0;i<comment_item_outers.length;i++){
        if(comment_item_outers[i].dataset.value===postId){
            comment_item_outer=comment_item_outers[i];
            console.log(comment_item_outers[i].value)
            console.log(comment_item_outer)
        }
    }
    comment_item_outer.innerHTML = '';
    currentPage=1;
    totalCommentsCount=0;

    // 初始化加载第一页
    loadComments(postIdNum,currentPage);


}
function publish(postId) {
    currentPostId = Number(postId);
    let comment_input_detail;
    let content;
    let comment_input_details = document.getElementsByClassName('comment-input-detail');
    for(let i=0;i<comment_input_details.length;i++){
        if( comment_input_details[i].dataset.value===postId){
            comment_input_detail=comment_input_details[i]
            content = comment_input_detail.value;
            console.log(content)
            console.log(comment_input_detail)
        }
    }

    $.ajax({
        url: `/posts/comment`,
        type: 'POST',
        data: {postId: currentPostId, content: content},
        success: function(result) {
            showCustomAlert('评论成功', 3000);
            console.log(result);
            comment_input_detail.value = '';

            // 重置分页状态，重新加载评论
            currentPage = 1;
            hasMoreData = true;

            // 清空现有评论，加载第一页
            let comment_item_outer;
            let  comment_item_outers = document.getElementsByClassName('comment-item-outer');
            for(let i=0;i<comment_item_outers.length;i++){
                if( comment_item_outers[i].dataset.value===postId){
                    comment_item_outer =comment_item_outers[i]


                }
            }
            comment_item_outer.innerHTML = '';
            loadComments(currentPostId, currentPage);

        },
        error: function(error) {
            showCustomAlert('评论失败: ' + error.status + ' ' + error.statusText, 3000);
            console.log(error);
        }
    });



}
// 加载评论函数

function loadComments(postIdNum,page) {
    isLoading = true;
    $.ajax({
        url: `/postsComments?postId=${postIdNum}&pageNum=${page}`,
        type: 'GET',
        success: function(result) {
            const id = result.userId;
            const comments = result.comments;
            const commentUsers = result.commentUsers;
            totalPages = result.totalPages; // 更新总页数
            // **更新累计评论数**
            // totalCommentsCount += comments.length;
            console.log(result)
            console.log(id)
            // 首次加载时初始化列表

            let commentListHTML = comments.length === 0 ?
                '<div class="empty-comment" xmlns="http://www.w3.org/1999/html"><i class="iconfont cat">&#xe61c;</i><br><span >暂无评论</span></div>' :
                comments.map((comment, i) => `
                            <div class="comment-item" style="padding-top: 10px;">
                                <div class="comment-user">
                                    <img src="${commentUsers[i].avatar}" alt="用户头像" class="avatar">
                                    <span class="username">${commentUsers[i].username}</span>
                                </div>
                                <div class="comment-content" data-value="${commentUsers[i].userId}">
                                    <p>${comment.content}</p>
                                    <span class="comment-time">${comment.createdAt}</span>
                                </div>
                                <div class="comment-actions">
                                    <span class="reply-icon" data-value="${comment.id}"><i class="iconfont comment-delete comment_like_icon">&#xe653;</i>点赞</span>
                                    <span class="share-icon2" data-value="${comment.id}"><i class="iconfont comment-delete">&#xe63f;</i>删除</span>
                                </div>
                            </div>
                        `).join('');
            const string=`<div class="detail-comment">进入详情页查看全部评论~</div>`
            const comment_item_outers = document.getElementsByClassName('comment-item-outer');
            let comment_item_outer;
            for(let i=0;i<comment_item_outers.length;i++){
                if(Number(comment_item_outers[i].dataset.value)===postIdNum){
                    comment_item_outer=comment_item_outers[i];
                }
            }


            if (page === 1) {

                comment_item_outer.innerHTML = commentListHTML; // 替换内容
                comment_item_outer.innerHTML+=string;
            }



            const pageSize = 5; // 根据后端接口设置
            const startIndex = (page - 1) * pageSize;
            const endIndex = page * pageSize - 1;

            const allShareIcons = document.getElementsByClassName('share-icon2');
// 提取当前页的删除按钮（基于页码和每页条数）
            const currentPageShareIcons = Array.from(allShareIcons).slice(startIndex, endIndex + 1);
            const replyIcons = document.getElementsByClassName('reply-icon');
            const commentLikeIcons = document.getElementsByClassName('comment_like_icon');
            console.log(commentUsers)

            for (let i = 0; i < comments.length; i++) {
                const commentUser = commentUsers[i];

                console.log(commentUser.id)
                if (String(id) === String(commentUser.id)) {
                    const shareIcon = currentPageShareIcons[i]; // 当前页内的相对索引
                    console.log(shareIcon)
                    shareIcon.style.display = 'block';
                    console.log(1111)
                }
            }

            // 绑定删除事件
            Array.from(currentPageShareIcons).forEach(shareIcon => {
                shareIcon.addEventListener('click', () => {
                    const commentId = Number(shareIcon.dataset.value);
                    console.log(commentId)
                    $.ajax({
                        url: `/posts/comment/user`,
                        type: 'POST',
                        data: { commentId:commentId },
                        success: (result) => {
                            showCustomAlert('删除成功', 3000);
                            totalCommentsCount = 0;
                            // 删除后重新加载当前页（可选：优化为局部删除）
                            if (comments.length === 0 && currentPage > 1) {
                                currentPage--;
                                // 重新加载上一页
                            }
                            loadComments(postIdNum, currentPage);
                        },
                        error: (error) => {
                            showCustomAlert('删除失败: ' + error.statusText, 3000);
                        }
                    });
                });
            });

            // 绑定点赞事件
            Array.from(replyIcons).forEach((replyIcon, i) => {
                replyIcon.addEventListener('click', () => {
                    const commentId = Number(replyIcon.dataset.value);
                    if (replyIcon.style.color === 'red') {
                        // 取消点赞
                        $.ajax({
                            url: `/comments/cancelLike`,
                            type: 'POST',
                            data: { commentsId: commentId },
                            success: () => {
                                showCustomAlert('取消点赞成功', 3000);
                                commentLikeIcons[i].style.color = 'rgb(82, 91, 100)';
                                replyIcon.style.color = 'rgb(82, 91, 100)';
                            }
                        });
                    } else {
                        // 点赞
                        $.ajax({
                            url: `/comments/like`,
                            type: 'POST',
                            data: {commentsId: commentId  },
                            success: () => {
                                showCustomAlert('点赞成功', 3000);
                                commentLikeIcons[i].style.color = 'red';
                                replyIcon.style.color = 'red';
                            }
                        });
                    }
                });
            });

            // 初始化点赞状态
            comments.forEach((comment, i) => {
                if (comment.isLiked) {
                    commentLikeIcons[i].style.color = 'red';
                    replyIcons[i].style.color = 'red';
                }
            });

            isLoading = false; // 加载完成
        },
        error: (error) => {
            currentPage--; // 加载失败时回退页码
            isLoading = false;
            showCustomAlert('加载评论失败: ' + error.statusText, 3000);
        }
    });


}